package com.xiaoxing.salesclient.mvp.ui.activity;

import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;

import io.reactivex.Observable;
import io.reactivex.Observer;
import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Predicate;

import com.alibaba.android.arouter.facade.annotation.Autowired;
import com.alibaba.android.arouter.facade.annotation.Route;
import com.alibaba.android.arouter.launcher.ARouter;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.jess.arms.base.BaseActivity;
import com.jess.arms.di.component.AppComponent;
import com.jess.arms.utils.ArmsUtils;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.constant.SpinnerStyle;
import com.scwang.smartrefresh.layout.header.ClassicsHeader;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;
import com.xiaoxing.gifloadingview.LoadingDialogUtil;
import com.xiaoxing.salesclient.di.component.DaggerXuanZeFuWuRenYuanComponent;
import com.xiaoxing.salesclient.di.module.XuanZeFuWuRenYuanModule;
import com.xiaoxing.salesclient.mvp.contract.XuanZeFuWuRenYuanContract;
import com.xiaoxing.salesclient.mvp.model.entity.Staffs;
import com.xiaoxing.salesclient.mvp.model.entity.Transfer;
import com.xiaoxing.salesclient.mvp.model.entity.TransferXuanZe;
import com.xiaoxing.salesclient.mvp.model.entity.Transfered;
import com.xiaoxing.salesclient.mvp.presenter.XuanZeFuWuRenYuanPresenter;
import com.xiaoxing.salesclient.mvp.ui.adapter.XuanZeFuWuRenYuanAdapter;
import com.xiaoxing.salesclient.mvp.ui.inter.ZhuangJie;
import com.xiaoxing.salesclient.mvp.ui.popup.XuanZeFuWuRenYuanPopup;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;

import butterknife.BindView;
import io.reactivex.Observable;
import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Consumer;
import me.jessyan.armscomponent.commonres.utils.ToolbarUtils;
import me.jessyan.armscomponent.commonsdk.core.BaseConstants;
import me.jessyan.armscomponent.commonsdk.core.RouterHub;
import retrofit2.Retrofit;
import xiaoxing.com.salesclient.R;
import xiaoxing.com.salesclient.R2;

import static com.jess.arms.utils.Preconditions.checkNotNull;


@Route(path = RouterHub.SALES_CLIENT_XUAN_ZE_FU_WU_REN_YUAN_ACTIVITY)
public class XuanZeFuWuRenYuanActivity extends BaseActivity<XuanZeFuWuRenYuanPresenter> implements XuanZeFuWuRenYuanContract.View, OnRefreshListener, ZhuangJie {


    private static boolean mIsNeedDemo = true;
    @BindView(R2.id.empty_text)
    TextView empty_text;
    @BindView(R2.id.empty_image)
    ImageView empty_image;

    @BindView(R2.id.empty)
    View mEmptyLayout;
    @BindView(R2.id.recyclerView)
    RecyclerView mRecyclerView;
    @BindView(R2.id.refreshLayout)

//    @Autowired
//    String order_id_zhuan_jie;
//    private String mOrderId;
//    private String xiaoXing;


            RefreshLayout mRefreshLayout;
    private XuanZeFuWuRenYuanAdapter mAdapter;
    private List<Staffs.DataBean> mDataBeanList = new ArrayList<>();

    @Override
    public void setupActivityComponent(@NonNull AppComponent appComponent) {
        DaggerXuanZeFuWuRenYuanComponent //如找不到该类,请编译一下项目
                .builder()
                .appComponent(appComponent)
                .xuanZeFuWuRenYuanModule(new XuanZeFuWuRenYuanModule(this))
                .build()
                .inject(this);

        ARouter.getInstance().inject(this);
    }

    @Override
    public int initView(@Nullable Bundle savedInstanceState) {
        return R.layout.activity_xuan_ze_fu_wu_ren_yuan; //如果你不需要框架帮你设置 setContentView(id) 需要自行设置,请返回 0
    }

    @Override
    public void initData(@Nullable Bundle savedInstanceState) {

//        mOrderId = getIntent().getExtras().getString("order_id_zhuan_jie");

        ToolbarUtils.initToolbarTitleBack(this, "選擇服務人員");
        initRefreshLayout();
        initRecyclerView();
        initEmpty();
//        intervalTransfered();

        mPresenter.staffs(mSharedPreferencesHelper.getString(BaseConstants.TOKEN));

    }

    private void initRefreshLayout() {
        mRefreshLayout.setRefreshHeader(new ClassicsHeader(this).setSpinnerStyle(SpinnerStyle.FixedBehind).setPrimaryColorId(R.color.public_colorPrimary).setAccentColorId(android.R.color.white));
        mRefreshLayout.setOnRefreshListener(this);
        mRefreshLayout.autoRefresh();
        mRefreshLayout.setEnableLoadMore(false);
    }

    private void initRecyclerView() {
        mRecyclerView.setLayoutManager(new GridLayoutManager(XuanZeFuWuRenYuanActivity.this, 2));
//        mRecyclerView.addItemDecoration(new DividerItemDecoration(XuanZeFuWuRenYuanActivity.this, VERTICAL));
        mRecyclerView.setItemAnimator(new DefaultItemAnimator());
        mRecyclerView.setAdapter(mAdapter = new XuanZeFuWuRenYuanAdapter(XuanZeFuWuRenYuanActivity.this, mDataBeanList));

        mAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
//                Utils.navigation(XuanZeFuWuRenYuanActivity.this, RouterHub.SALES_CLIENT_ZUI_XIN_XIAO_XI_XIANG_QING_ACTIVITY);
                String mOrderId = getIntent().getExtras().getString("order_id_zhuan_jie");
                new XuanZeFuWuRenYuanPopup(XuanZeFuWuRenYuanActivity.this, XuanZeFuWuRenYuanActivity.this, mOrderId, mDataBeanList.get(position).getStaff_id(), mDataBeanList.get(position).getCover()).showPopupWindow();
            }
        });
    }

    private void initEmpty() {
        empty_image.setImageResource(R.drawable.no_data);
        empty_text.setTextColor(getResources().getColor(R.color.public_no_data));
        empty_text.setText("暫無消息,下拉更新");
    }

    @Override
    public void onRefresh(@NonNull RefreshLayout refreshLayout) {

        mRefreshLayout.finishRefresh();
        mEmptyLayout.setVisibility(View.GONE);

    }

    @Override
    public void showLoading() {
//        LoadingDialogUtil.showGifdialog2(getSupportFragmentManager(), R.drawable.public_loading);
    }

    @Override
    public void hideLoading() {
//        LoadingDialogUtil.dismissDialog();
    }

    @Override
    public void showMessage(@NonNull String message) {
        checkNotNull(message);
        ArmsUtils.snackbarText(message);
    }

    @Override
    public void launchActivity(@NonNull Intent intent) {
        checkNotNull(intent);
        ArmsUtils.startActivity(intent);
    }

    @Override
    public void killMyself() {
        finish();
    }

    @Override
    public void staffsSuccessed(Staffs staffs) {

        if (staffs != null && staffs.getData() != null && staffs.getData().size() > 0) {
            mEmptyLayout.setVisibility(View.GONE);
            mRecyclerView.setVisibility(View.VISIBLE);
            mDataBeanList.clear();
            mDataBeanList.addAll(staffs.getData());
            mAdapter.notifyDataSetChanged();
        } else {
            mEmptyLayout.setVisibility(View.VISIBLE);
            mRecyclerView.setVisibility(View.GONE);
        }

    }

    @Override
    public void transferSuccessed(TransferXuanZe transferXuanZe) {

        ArmsUtils.makeText(this, transferXuanZe.getMsg());
    }

    @Override
    public void transferedSuccessed(Transfered transfered) {

    }

    @Override
    public void zhuanJie(String order_id, String staff_id) {
        mPresenter.transfer(mSharedPreferencesHelper.getString(BaseConstants.TOKEN), order_id, staff_id);
    }

    private void intervalTransfered() {

        /*
         * 步骤1：采用interval（）延迟发送
         * 注：此处主要展示无限次轮询，若要实现有限次轮询，仅需将interval（）改成intervalRange（）即可
         **/
        Observable.interval(2, 10, TimeUnit.SECONDS)
                // 参数说明：
                // 参数1 = 第1次延迟时间；
                // 参数2 = 间隔时间数字；
                // 参数3 = 时间单位；
                // 该例子发送的事件特点：延迟2s后发送事件，每隔1秒产生1个数字（从0开始递增1，无限个）

                /*
                 * 步骤2：每次发送数字前发送1次网络请求（doOnNext（）在执行Next事件前调用）
                 * 即每隔1秒产生1个数字前，就发送1次网络请求，从而实现轮询需求
                 **/
                .doOnNext(new Consumer<Long>() {
                    @Override
                    public void accept(Long integer) throws Exception {
                        Log.d(TAG, "第 " + integer + " 次轮询");

                        mPresenter.transfered(mSharedPreferencesHelper.getString(BaseConstants.TOKEN));

                    }
                }).subscribe(new Observer<Long>() {
            @Override
            public void onSubscribe(Disposable d) {

            }

            @Override
            public void onNext(Long value) {

            }

            @Override
            public void onError(Throwable e) {
                Log.d(TAG, "对Error事件作出响应");
            }

            @Override
            public void onComplete() {
                Log.d(TAG, "对Complete事件作出响应");
            }
        });


    }

}
